#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>

namespace server
{
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,
        ACCEPT_ERROR
    };
    static const uint16_t gport = 8080;
    static const int gbacklog = 128;
    class server
    {
    public:
        server(const uint16_t &port = gport) : _port(port), _listensock(-1)
        {
        }

        void initServer()
        {
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                exit(SOCKET_ERROR);
            }
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = 0;
            int n = bind(_listensock, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                exit(BIND_ERROR);
            }
            int n = listen(_listensock, gbacklog);
            if (n < 0)
            {
                exit(LISTEN_ERROR);
            }
        }
        void fun(int sock)
        {
        }

        void start()
        {
            while (1)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    continue;
                }
                pid_t pid = fork();
                if (pid == 0)
                {
                    close(_listensock);
                    if (fork() > 0)
                    {
                        exit(0);
                    }
                    fun(sock);
                    close(sock);
                }
                else
                {
                    close(sock);
                    int status;
                    int ret = waitpid(pid, &status, 0);
                    std::cout << "wait success:" << ret << std::endl;
                }
            }
        }

    private:
        int _listensock;
        uint16_t _port;
    };
};